package org.df.ulab.bot.plugins.pmi.command;

import org.df.ulab.bot.api.command.CommandFactory;
import org.df.ulab.bot.api.command.InitializationRequired;
import org.df.ulab.bot.api.message.ImMessage;
import org.df.ulab.bot.api.pmi.entity.Issue;
import org.df.ulab.bot.plugins.pmi.HandlerSession;
import org.df.ulab.bot.plugins.pmi.commons.UserSettings;
import org.df.ulab.bot.util.command.InternetCommand;
import org.df.ulab.bot.util.message.BasicMsgInterpreter;
import org.df.ulab.util.formatter.Formatter;

/**
 * @author Daniel Filgueiras
 * @since 19/06/2011
 */
@CommandFactory(BasicMsgInterpreter.class)
@InitializationRequired
public class ShowWorkedTime extends InternetCommand {

	private String issueId;
	
	@Override
	public boolean proccess(ImMessage message) {
		
		UserSettings settings = HandlerSession.getUserSettings(remoteId);
		
		Issue issue = null;
		boolean myWorkedTime = false;
		
		StringBuilder builder =	new StringBuilder();
		
		if (issueId == null || issueId.length() == 0) {
			issue = HandlerSession.getDatabase().getIssue(settings.getWorkingIssue());
			myWorkedTime = true;
		} else {
			issue = HandlerSession.getDatabase().getIssue(Long.parseLong(issueId));
		}
		

		if (issue == null) {
			service.reply(message, "Unknown issue");
			return true;
		} else if (myWorkedTime && settings.getWorkingIssue() == 0) {
			service.reply(message, "You are not working at any issue");
			return true;
		} else if (myWorkedTime && settings.getWorkingIssue() != issue.getId()) {
			service.reply(message, "You are not working on this issue");
			return true;
		}
		
		if (myWorkedTime) {
			String time = new Formatter().formatTimeInMilliToHour(settings.getWorkedTime());
			builder.append("You have worked (")
				.append(time)
				.append(") on issue #")
				.append(issue.getId())
				.append(": *\"")
				.append(issue.getSummary())
				.append("\"*");
		} else {
			String time = new Formatter().formatTimeInMilliToHour((long)(issue.getSpendTime() * 1000L * 60L * 60L));
			builder.append("Was spent (")
				.append(time)
				.append(") on issue #")
				.append(issue.getId())
				.append(": *\"")
				.append(issue.getSummary())
				.append("\"*");
		}
			
		service.reply(message, builder);
		
		return true;
	}
}
